cmake_minimum_required(VERSION 3.18 FATAL_ERROR)

file(GLOB_RECURSE PRCC_SRC *.*)

find_package(Threads REQUIRED)

# find LLVM, create target libclang

if (WIN32)
  set(LLVM_INSTALL_ROOT "C:/Program Files/LLVM" CACHE STRING "LLVM's Install directory, e.g. C:/Program Files/LLVM")
  if(EXISTS ${LLVM_INSTALL_ROOT} AND EXISTS ${LLVM_INSTALL_ROOT}/include AND EXISTS ${LLVM_INSTALL_ROOT}/lib AND EXISTS ${LLVM_INSTALL_ROOT}/bin)
    add_library(libclang SHARED IMPORTED)
    set_target_properties(
      libclang
      PROPERTIES
      IMPORTED_LOCATION ${LLVM_INSTALL_ROOT}/bin/libclang.dll
      IMPORTED_IMPLIB ${LLVM_INSTALL_ROOT}/lib/libclang.lib
      INTERFACE_INCLUDE_DIRECTORIES ${LLVM_INSTALL_ROOT}/include
    )
    add_library(Clang::Clang ALIAS libclang)
  else()
    message(FATAL_ERROR "LLVM ROOT IS NOT VALID!!")
  endif()
elseif(UNIX)
  set(LLVM_INSTALL_ROOT "/usr/lib/llvm-15" CACHE STRING "LLVM's Install directory, e.g. /usr/lib/llvm-15")
  if(EXISTS ${LLVM_INSTALL_ROOT} AND EXISTS ${LLVM_INSTALL_ROOT}/include AND EXISTS ${LLVM_INSTALL_ROOT}/lib)
    add_library(libclang SHARED IMPORTED)
    set_target_properties(
      libclang
      PROPERTIES
      IMPORTED_LOCATION ${LLVM_INSTALL_ROOT}/lib/libclang.so
      INTERFACE_INCLUDE_DIRECTORIES ${LLVM_INSTALL_ROOT}/include
    )
    add_library(Clang::Clang ALIAS libclang)
  else()
    message(FATAL_ERROR "LLVM ROOT IS NOT VALID!!")
  endif()
endif()

add_executable(codegen ${PRCC_SRC})
target_include_directories(codegen PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(codegen PRIVATE PkgConfig::Zstd Threads::Threads Clang::Clang)

if (WIN32)
  add_custom_command(
    TARGET codegen POST_BUILD
    # COMMAND ${CMAKE_COMMAND} -E echo "DLLS: $<TARGET_RUNTIME_DLLS:codegen>"
    COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_RUNTIME_DLLS:codegen> $<TARGET_FILE_DIR:codegen> COMMAND_EXPAND_LISTS
    COMMENT "Copy libclang DLLs"
  )
endif()
